using System;
using System.Collections;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using Elmah;

namespace OrbitOne.Elmah.Web.Services
{
    public class ServicesXmlFileErrorLog : XmlFileErrorLog
    {
        private static ErrorLog _defaultLog;

        public ServicesXmlFileErrorLog(IDictionary config) : base(config)
        {
        }

        public ServicesXmlFileErrorLog(string logPath) : base(logPath)
        {
        }

        public new static ErrorLog Default
        {
            get
            {
                if (_defaultLog == null)
                {
                    var logConfiguration = ConfigurationSettings.GetConfig("OrbitOne.Elmah/errorLog") as IDictionary;
                    if (logConfiguration != null)
                    {
                        _defaultLog = new ServicesXmlFileErrorLog(logConfiguration["LogPath"].ToString());
                    }
                    else
                    {
                        _defaultLog = new MemoryErrorLog();
                    }
                }
                return _defaultLog;
            }
        }

        public override string ApplicationName
        {
            get
            {
                return System.ServiceModel.OperationContext.Current.Host.BaseAddresses[0].ToString();
            }
        }

        public override string Log(Error error)
        {
            string errorId = Guid.NewGuid().ToString();
            string timeStamp = DateTime.Now.ToString("yyyy-MM-ddHHmmssZ", CultureInfo.InvariantCulture);
            string path = Path.Combine(LogPath, string.Format(@"error-{0}-{1}.xml", timeStamp, errorId));
            XmlTextWriter writer = new XmlTextWriter(path, Encoding.UTF8);
            try
            {
                error.ApplicationName = ApplicationName;
                writer.Formatting = Formatting.Indented;
                writer.WriteStartElement("error");
                writer.WriteAttributeString("errorId", errorId);
                error.ToXml(writer);
                writer.WriteEndElement();
                writer.Flush();
            }
            finally
            {
                writer.Close();
            }
            return errorId;
        }
    }
}